﻿using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Shared.CorsHelper
{
    /// <summary>
    /// 解决CORS跨域问题
    /// app.UseMiddleware[Shared.CorsHelper.CorsMiddleware]();
    /// 必须放在app.UseRouting()和app.UseEndpoints之间，不然也会报上述错误
    /// </summary>
    public class CorsMiddleware
    {
        private readonly RequestDelegate next;
        /// <summary>
        /// 解决CORS跨域问题
        /// app.UseMiddleware<Shared.CorsHelper.CorsMiddleware>();
        /// </summary>
        public CorsMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
            {
                context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
                context.Response.Headers.Add("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,CONNECT,OPTIONS,TRACE,PATCH");
                context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
                context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

                if (context.Request.Method.Equals("OPTIONS"))
                {
                    context.Response.StatusCode = StatusCodes.Status200OK;
                    return;
                }
            }
            await next(context);
        }
    }
}
